package com.returnsoft.softphone.eao;

import java.io.Serializable;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.returnsoft.softphone.entity.Server;
import com.returnsoft.softphone.exception.EaoExcepcion;

@LocalBean
@Stateless
public class ServerEao implements Serializable{
	
	private static final long serialVersionUID = 1L;

	@PersistenceContext(name = "CCenterEJB", unitName = "CCenterEJB")
	private EntityManager em;

	/*public List<Server> findAll() throws EaoExcepcion {
		try {
			TypedQuery<Server> q = em.createQuery("SELECT s FROM Server s",
					Server.class);
			List<Server> servers = q.getResultList();
			return servers;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}*/
	
	public Server findByCode(String code) throws EaoExcepcion {
		try {
			Query q = em.createQuery("SELECT s.id,s.ip,s.amiUser,s.amiPassword,s.amiPort,s.pbxDatabase FROM Server s where s.code=:code");
			q.setParameter("code", code);
			Object[] serverObject = (Object[]) q.getSingleResult();
			
			Integer id = (Integer) serverObject[0];
			String ip = (String) serverObject[1];
			String amiUser = (String) serverObject[2];
			String amiPassword = (String) serverObject[3];
			Integer amiPort = (Integer) serverObject[4];
			String pbxDatabase = (String) serverObject[5];
			
			Server server = new Server();
			server.setId(id);
			server.setIp(ip);
			server.setCode(code);
			server.setAmiPassword(amiPassword);
			server.setAmiUser(amiUser);
			server.setAmiPort(amiPort);
			server.setPbxDatabase(pbxDatabase);
			
			return server;
		} catch (NoResultException e) {
			return null;
		}  catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}
	

}
